<template>
  <div>
    <div class="anchor"></div>
    <div id="map1" class="map" tabindex="0"></div>
    <el-row>
      <el-button @click="changeMap" type="primary">互换地图</el-button>
      <el-button @click="moveLeft" type="primary">左移地图</el-button>
      <el-button @click="moveRight" type="primary">右移地图</el-button>
      <el-button @click="moveUp" type="primary">上移地图</el-button>
      <el-button @click="moveDown" type="primary">下移地图</el-button>
      <el-button @click="zoomIn" type="primary">放大</el-button>
      <el-button @click="zoomOut" type="primary">缩小</el-button>
      <el-button @click="movePoint" type="primary">移动红点</el-button>
      <el-button :plain="true" @click="open" type="primary">feature</el-button>
      {{ x }} ,{{ y }}
    </el-row>
  </div>
</template>

<script>
import f5polygon from "../assets/f5polygon";
// import f5a from "../assets/f5a";
import f5door from "../assets/f5door";
import "ol/ol.css";
import OSM from "ol/source/OSM";
import GeoJSON from "ol/format/GeoJSON";
import Map from "ol/Map";
import View from "ol/View";
import { Fill, Stroke, Style } from "ol/style";
import { Vector as VectorSource } from "ol/source";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { fromLonLat } from "ol/proj";
import Point from "ol/geom/Point";
import Feature from "ol/Feature";
import RegularShape from "ol/style/RegularShape";
import Overlay from "ol/Overlay";
import LineString from "ol/geom/LineString";

export default {
  data() {
    return {
      stepLen: 200, //步长
      routeLayer: {},
      map1: {},
      map2: {},
      features: 0,
      x: 40000,
      y: -9500,
      point: {},
      path: [
        { x: 40000, y: -9500 },
        { x: 20000, y: -5000 },
        { x: 30000, y: -6000 },
        { x: 30000, y: -9500 },
        { x: 57000, y: -102500 },
      ],
      styleFunction: {},
      vectorSource: {},
      vectorLayer: [],
      geojsonObject: f5polygon,
    };
  },

  methods: {
    //绘制路径图层
    drawLine() {
      this.routeLayer = new VectorLayer({
        source: new VectorSource({
          features: [],
        }),
      });
      this.map1.addLayer(this.routeLayer);

      let comDots = [];
      let wireFeature = {};
      this.path.forEach((item) => {
        comDots.push([item.x, item.y]);
        wireFeature = new Feature({
          geometry: new LineString(comDots),
        });
        wireFeature.setStyle(
          new Style({
            stroke: new Stroke({
              // 设置边的样式
              color: "rgb(21, 106, 158)",
              width: 3,
            }),
          })
        );
        this.routeLayer.getSource().addFeatures([wireFeature]);
      });
    },
    //移动点
    movePoint() {
      let tempPath = this.path;
      let index = 1; //记录路径点的下标
      let len = tempPath.length; //记录原来的path数组长度
      let v = tempPath[index];
      //根据步长算出一段路径分为多少步,每步x方向移动距离和y方向移动距离
      let steps =
        Math.sqrt(
          (v.x - this.x) * (v.x - this.x) + (v.y - this.y) * (v.y - this.y)
        ) / this.stepLen;
      let mx = (v.x - this.x) / steps;
      let my = (v.y - this.y) / steps; //分成steps份
      //定时器
      let timer = window.setInterval(() => {
        this.x += mx;
        this.y += my;
        this.point.setPosition([this.x, this.y]);

        //test:改变路径图层
        tempPath[0].x = this.x;
        tempPath[0].y = this.y;
        this.map1.removeLayer(this.routeLayer);
        this.drawLine(); //根据调整后的路径重画

        if (
          Math.abs(this.x - v.x) < this.stepLen + 1 &&
          Math.abs(this.y - v.y) < this.stepLen + 1
        ) {
          index++;
          console.log(index);
          if (index >= len) {
            clearInterval(timer);
          } else {
            this.x = v.x;
            this.y = v.y;
            v = tempPath[2];
            steps =
              Math.sqrt(
                (v.x - this.x) * (v.x - this.x) +
                  (v.y - this.y) * (v.y - this.y)
              ) / this.stepLen;
            mx = (v.x - this.x) / steps;
            my = (v.y - this.y) / steps;
          }
          tempPath.shift(); //删掉已经走过的点
          console.log(steps);
        }
      }, 50);
    },
    changeMap() {
      this.map1.setTarget("map2");
      this.map2.setTarget("map1");
    },
    moveLeft() {
      var view = this.map1.getView();
      var mapCenter = view.getCenter();
      // 让地图中心的x值增加，即可使得地图向左移动，增加的值根据效果可自由设定
      mapCenter[0] += 4000;
      view.setCenter(mapCenter);
      this.map1.render();
    },
    moveRight() {
      var view = this.map1.getView();
      var mapCenter = view.getCenter();
      // 让地图中心的x值减小，即可使得地图向右移动，增加的值根据效果可自由设定
      mapCenter[0] -= 4000;
      view.setCenter(mapCenter);
      this.map1.render();
    },
    moveUp() {
      var view = this.map1.getView();
      var mapCenter = view.getCenter();
      // 让地图中心的y值减少，即可使得地图向上移动，减少的值根据效果可自由设定
      mapCenter[1] -= 1000;
      view.setCenter(mapCenter);
      this.map1.render();
    },
    moveDown() {
      var view = this.map1.getView();
      var mapCenter = view.getCenter();
      // 让地图中心的y值增加，即可使得地图向下移动，增加的值根据效果可自由设定
      mapCenter[1] += 1000;
      view.setCenter(mapCenter);
      this.map1.render();
    },
    zoomIn() {
      var view = this.map1.getView();
      // 让地图的zoom增加1，从而实现地图放大
      view.setZoom(view.getZoom() + 1);
    },
    zoomOut() {
      var view = this.map1.getView();
      // 让地图的zoom减小1，从而实现地图缩小
      view.setZoom(view.getZoom() - 1);
    },
    open() {
      this.$message("feature:" + this.features);
    },
  },

  mounted() {
    const styles = {
      MultiLineString: new Style({
        stroke: new Stroke({
          color: "green",
          width: 3,
        }),
      }),
      MultiPolygon: new Style({
        stroke: new Stroke({
          color: "grey",
          width: 1,
        }),
        fill: new Fill({
          color: "rgba(240,248,255, 0.7)",
        }),
      }),
    };

    this.styleFunction = function (feature) {
      return styles[feature.getGeometry().getType()];
    };

    let vectorSource1 = new VectorSource({
      features: new GeoJSON().readFeatures(f5polygon),
    });
    let vectorSource2 = new VectorSource({
      features: new GeoJSON().readFeatures(f5door),
    });
    this.vectorLayer.push(
      new VectorLayer({
        source: vectorSource1,
        style: this.styleFunction,
      })
    );
    this.vectorLayer.push(
      new VectorLayer({
        source: vectorSource2,
        style: this.styleFunction,
      })
    );

    this.features = this.vectorLayer[0].getSource().getFeatures().length;

    this.map1 = new Map({
      layers: this.vectorLayer,
      target: "map1",
      view: new View({
        center: [this.x, this.y],
        //projection: 'EPSG:3857',
        // projection: 'EPSG:2406',
        zoom: 9,
      }),
    });

    //画一个点并添加到地图1上
    this.point = new Overlay({
      element: document.querySelector(".anchor"),
    });
    // 需要设置附加到地图上的位置
    this.point.setPosition([this.x, this.y]);
    this.point.setPositioning("center-center");
    // 然后添加到map上
    this.map1.addOverlay(this.point);
    //画路线
    this.drawLine();
  },
};
</script>



<style scoped>
.map {
  width: 100%;
  height: 800px;
}

.anchor {
  display: inline-block;
  height: 15px;
  width: 15px;
  background-color: red;
  border-radius: 50%;
}
</style>